<?php
require 'db_config.php';
require 'mailer.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username']);
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $email = trim($_POST['email']);
    
    // 生成验证码 (用户名+时间戳的哈希)
    $verification_code = md5($username . time());
    
    // 设置过期时间 (1小时后)
    $expires_at = date('Y-m-d H:i:s', strtotime('+1 hour'));
    
    try {
        $stmt = $pdo->prepare("INSERT INTO users (username, password, email, verification_code, expires_at) 
                              VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$username, $password, $email, $verification_code, $expires_at]);
        
        // 发送验证邮件
        $verification_link = "http://127.0.0.1/verify.php?user=".urlencode($username)."&code=$verification_code";
        sendVerificationEmail($email, $username, $verification_link);
        
        echo "注册成功! 请检查您的邮箱激活账户。";
    } catch (PDOException $e) {
        if ($e->errorInfo[1] == 1062) {
            echo "用户名或邮箱已被注册!";
        } else {
            echo "注册失败: " . $e->getMessage();
        }
    }
}
?>

<form method="post">
    昵称: <input type="text" name="username" required><br>
    密码: <input type="password" name="password" required><br>
    邮箱: <input type="email" name="email" required><br>
    <button type="submit">注册</button>
</form>